<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDidalog()"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        :data="catelist"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-index="true"
        index-text="#"
        :border="true"
        :stripe="true"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="!scope.row.cat_deleted"></i>
          <i class="el-icon-error" v-else></i>
        </template>
        <!-- 权限等级 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="editingdialog(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            @click="removeCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCatedialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <!-- options 用来指定数据源 -->
          <!-- props 用来指定配置对象 -->
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="castaderProps"
            @change="parentCateChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editingdialogVisible"
      width="50%"
    >
      <el-form
        :model="editCate"
        :rules="editCateRules"
        ref="editingruleFormRef"
        label-width="100px"
      >
        <el-form-item label="活动名称" prop="cat_name">
          <el-input v-model="editCate.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editingdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editingclickVisible">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Cate",
  data() {
    return {
      //查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品分类的数据列表
      catelist: [],
      // 总数据条数
      total: 0,
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          //定义为模板列
          type: "template",
          //模板名称
          template: "isok",
        },
        {
          label: "排序",
          //定义为模板列
          type: "template",
          //模板名称
          template: "order",
        },
        {
          label: "操作",
          //定义为模板列
          type: "template",
          //模板名称
          template: "opt",
        },
      ],
      //控制添加分类对话框显示与隐藏
      addCatedialogVisible: false,
      //添加分类
      addCateForm: {
        // 将要添加分类的名称
        cat_name: "",
        // 父级分类的ID
        cat_pid: 0,
        // 分类层级,默认要添加的是1级分类
        cat_level: 0,
      },
      addCateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      parentCateList: [],
      // 指定级联选择器的配置属性
      castaderProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        checkStrictly: true,
      },
      //选中的父类分类的id数组
      selectedKeys: [],
      editCate: {},
      //编辑分类
      editingdialogVisible: false,
      editCateRules: {
        cat_name: [
          { required: true, message: "请输入要修改的信息", trigger: "blur" },
        ],
      },
      editCateId: 0,
      // 删除分类
      deldialogVisible: false,
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status != 200) {
        return this.$message.error("获取商品分类失败");
      }
      this.catelist = res.data.result;
      this.total = res.data.total;
    },
    //pageSize 改变时会触发	每页条数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },
    //currentPage 改变时会触发	当前页
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getCateList();
    },
    //添加商品分类
    showAddCateDidalog() {
      this.getParentCateList();
      this.addCatedialogVisible = true;
    },
    //获取父级分类
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status != 200) {
        return this.$message.error("获取商品分类失败");
      }
      this.parentCateList = res.data;
    },
    //选择项发生变化触发
    parentCateChange() {
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid =
          this.selectedKeys[this.selectedKeys.length - 1];
        this.addCateForm.cat_level = this.selectedKeys.length;
        return;
      }
      return;
    },
    addCate() {
      // console.log(this.addCateForm);
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) {
          this.addCatedialogVisible = false;

          return this.$message.error("添加分类失败!");
        }
        this.$message.success("添加分类成功!");
        this.getCateList();
        this.addCatedialogVisible = false;
      });
    },
    // 关闭对话框事件,重置表单数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
      this.selectdKeys = [];
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_pid = 0;
    },
    //编辑分类
    async editingdialog(cateInfo) {
      this.editCateId = cateInfo.cat_id;
      const { data: res } = await this.$http.get(
        "categories/" + cateInfo.cat_id
      );
      this.editCate = res.data;
      console.log(this.editCate);
      // console.log(res.data)
      this.editingdialogVisible = true;
    },
    //提交编辑分类
    async editingclickVisible() {
      const { data: res } = await this.$http.put(
        `categories/${this.editCateId}`,
        {
          cat_name: this.editCate.cat_name,
        }
      );
      if (res.meta.status !== 200) {
        this.editingdialogVisible = false;
        return this.$message.error("编辑分类失败!");
      }
      this.$message.success("编辑分类成功!");
      this.getCateList();
      this.editingdialogVisible = false;
    },
    // 删除分类
    removeCate(id) {
      this.$MessageBox("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`categories/${id}`);
          if (res.meta.status !== 200) {
            return this.$message.error("删除分类失败!");
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getCateList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang="less" scoped>
.el-icon-success {
  color: green;
}
.el-icon-error {
  color: red;
}
.el-row {
  margin-bottom: 10px;
}
.el-cascader {
  width: 100%;
}
</style>